import React, { useEffect, useState, useCallback } from 'react';
import { Card, Table, Tag, Empty, Typography, Space, DatePicker, Button, Input, Badge, Avatar, Tooltip, Modal, Descriptions } from 'antd';
import { SearchOutlined, ReloadOutlined, CheckCircleOutlined, CloseCircleOutlined, CalendarOutlined, InfoCircleOutlined, EnvironmentOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { fetchSignInHistory } from '../../store/slices/signInSlice';
import dayjs from 'dayjs';
import './index.scss';

const { Title, Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;

const History = () => {
  const dispatch = useDispatch();
  const { history, loading } = useSelector((state) => state.signIn);
  const [filteredData, setFilteredData] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [dateRange, setDateRange] = useState(null);
  const [refreshing, setRefreshing] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState(null);
  const [activeStatus, setActiveStatus] = useState(null); // null = all, 1 = success, 0 = failed
  const [dataFetched, setDataFetched] = useState(false);

  // 获取签到历史数据
  const fetchHistoryData = useCallback(async (force = false) => {
    // 如果数据已加载且不是强制刷新，直接返回
    if (dataFetched && !force) {
      return;
    }
    
    setRefreshing(true);
    try {
      console.log('开始获取签到历史数据...');
      const result = await dispatch(fetchSignInHistory({ forceRefresh: force, showMissed: true })).unwrap();
      console.log('获取到的签到历史数据:', result);
      setDataFetched(true);
    } catch (error) {
      console.error('获取签到历史失败:', error);
    } finally {
      setRefreshing(false);
    }
  }, [dispatch, dataFetched]);

  // 初始加载数据 - 只在组件挂载时执行一次
  useEffect(() => {
    fetchHistoryData();
  }, [fetchHistoryData]);

  // 添加调试日志，查看Redux状态
  useEffect(() => {
    console.log('当前Redux状态中的历史数据:', history);
    console.log('过滤后的数据:', filteredData);
  }, [history, filteredData]);

  // 应用过滤器的函数
  const applyFilters = useCallback(() => {
    if (!Array.isArray(history)) {
      console.log('历史数据不是数组:', history);
      setFilteredData([]);
      return;
    }
    
    console.log('应用过滤器前的历史数据:', history);
    
    let filtered = [...history];
    
    // Apply text search if specified
    if (searchText) {
      const searchLower = searchText.toLowerCase();
      filtered = filtered.filter(record => 
        (record.course_name && record.course_name.toLowerCase().includes(searchLower)) ||
        (record.course_id && String(record.course_id).toLowerCase().includes(searchLower)) ||
        (record.task_description && record.task_description.toLowerCase().includes(searchLower)) ||
        (record.sign_in_task_id && record.sign_in_task_id.toString().includes(searchLower))
      );
    }
    
    // Apply date range if specified
    if (dateRange && dateRange[0] && dateRange[1]) {
      const startTimestamp = dateRange[0].startOf('day').valueOf() / 1000;
      const endTimestamp = dateRange[1].endOf('day').valueOf() / 1000;
      
      filtered = filtered.filter(record => {
        // 确保record.sign_in_time存在
        const timestamp = record.sign_in_time || record.end_time || 0;
        return timestamp >= startTimestamp && timestamp <= endTimestamp;
      });
    }
    
    // Apply status filter if specified
    if (activeStatus !== null) {
      filtered = filtered.filter(record => record.status === activeStatus);
    }
    
    console.log('应用过滤器后的数据:', filtered);
    setFilteredData(filtered);
  }, [history, searchText, dateRange, activeStatus]);

  // 过滤器变化时重新应用
  useEffect(() => {
    applyFilters();
  }, [applyFilters]);

  // 手动刷新按钮处理函数
  const handleRefresh = useCallback(() => {
    if (refreshing) return; // 如果正在刷新中，直接返回
    fetchHistoryData(true); // 强制刷新
  }, [fetchHistoryData, refreshing]);

  const formatTime = (timestamp) => {
    if (!timestamp) return '未记录';
    return new Date(timestamp * 1000).toLocaleString();
  };
  
  const formatDate = (timestamp) => {
    if (!timestamp) return '未记录';
    return new Date(timestamp * 1000).toLocaleDateString();
  };
  
  const formatTimeOnly = (timestamp) => {
    if (!timestamp) return '未记录';
    return new Date(timestamp * 1000).toLocaleTimeString();
  };
  
  const resetFilters = () => {
    setSearchText('');
    setDateRange(null);
    setActiveStatus(null);
  };
  
  const showRecordDetails = (record) => {
    setSelectedRecord(record);
    setDetailModalVisible(true);
  };
  
  const handleStatusFilterChange = (status) => {
    setActiveStatus(activeStatus === status ? null : status);
  };
  
  // 根据签到时间生成日期分组
  const groupRecordsByDate = () => {
    const groups = {};
    filteredData.forEach(record => {
      const date = formatDate(record.sign_in_time);
      if (!groups[date]) {
        groups[date] = [];
      }
      groups[date].push(record);
    });
    return groups;
  };
  
  // 统计数据
  const getStatistics = () => {
    if (!filteredData || !Array.isArray(filteredData)) {
      return { total: 0, success: 0, failed: 0, missed: 0, successRate: 0 };
    }
    
    const total = filteredData.length;
    const success = filteredData.filter(record => record.status === 1).length;
    const failed = filteredData.filter(record => record.status === 0).length;
    const missed = filteredData.filter(record => record.status === 0 && !record.id).length;
    
    const successRate = total > 0 ? Math.round((success / total) * 100) : 0;
    
    return { total, success, failed, missed, successRate };
  };
  
  const stats = getStatistics();

  const columns = [
    {
      title: '签到时间',
      dataIndex: 'sign_in_time',
      key: 'sign_in_time',
      render: (timestamp, record) => {
        // 对于未签到的记录，显示任务结束时间
        const displayTime = timestamp || record.end_time;
        return (
          <Space direction="vertical" size={0}>
            <Text strong>{formatDate(displayTime)}</Text>
            <Text type="secondary">{formatTimeOnly(displayTime)}</Text>
            {record.status === 0 && !record.id && (
              <Text type="danger" style={{ fontSize: '12px' }}>未签到</Text>
            )}
          </Space>
        );
      },
      sorter: (a, b) => {
        const timeA = a.sign_in_time || a.end_time || 0;
        const timeB = b.sign_in_time || b.end_time || 0;
        return timeA - timeB;
      },
      defaultSortOrder: 'descend',
      width: 140,
    },
    {
      title: '课程信息',
      dataIndex: 'course_name',
      key: 'course_name',
      render: (text, record) => (
        <div className="course-info">
          <span className="course-name">{text || '未知课程'}</span>
          <span className="course-id">ID: {record.course_id || '未知'}</span>
        </div>
      ),
    },
    {
      title: '签到任务',
      dataIndex: 'task_description',
      key: 'task_description',
      render: (text, record) => (
        <div className="task-info">
          <Tooltip title="查看详情">
            <Button 
              type="link" 
              icon={<InfoCircleOutlined />} 
              onClick={(e) => {
                e.stopPropagation();
                showRecordDetails(record);
              }}
              size="small"
            >
              {text || `签到任务 #${record.sign_in_task_id}`}
            </Button>
          </Tooltip>
        </div>
      ),
      width: 200,
    },
    {
      title: '签到状态',
      dataIndex: 'status',
      key: 'status',
      render: (status, record) => {
        // 判断是否为未签到记录（status=0且没有id）
        if (status === 0 && !record.id) {
          return (
            <Tag 
              icon={<CloseCircleOutlined />}
              color="warning"
              className="status-tag"
            >
              未签到
            </Tag>
          );
        }
        
        return (
          <Tag 
            icon={status === 1 ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
            color={status === 1 ? 'success' : 'error'}
            className="status-tag"
          >
            {status === 1 ? '签到成功' : '签到失败'}
          </Tag>
        );
      },
      width: 120,
      align: 'center',
    },
    {
      title: '位置信息',
      dataIndex: 'location',
      key: 'location',
      render: (text) => text ? (
        <Tooltip title={text}>
          <Space>
            <EnvironmentOutlined style={{ color: '#1890ff' }} />
            <Text ellipsis>{text}</Text>
          </Space>
        </Tooltip>
      ) : '未记录',
      width: 140,
    }
  ];

  return (
    <div className="history-page">
      <Card 
        title={
          <div className="card-header">
            <Title level={4}>签到历史记录</Title>
            <Space>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={handleRefresh}
                loading={refreshing}
              >
                刷新
              </Button>
            </Space>
          </div>
        }
        className="history-card"
      >
        <div className="statistics-section">
          <div className="stat-item">
            <div className="stat-title">总签到次数</div>
            <div className="stat-value">{stats.total}</div>
          </div>
          <div className="stat-item success">
            <div className="stat-title">成功签到</div>
            <div className="stat-value">{stats.success}</div>
          </div>
          <div className="stat-item failed">
            <div className="stat-title">失败签到</div>
            <div className="stat-value">{stats.failed}</div>
          </div>
          <div className="stat-item missed">
            <div className="stat-title">未签到</div>
            <div className="stat-value">{stats.missed}</div>
          </div>
          <div className="stat-item rate">
            <div className="stat-title">签到成功率</div>
            <div className="stat-value">{stats.successRate}%</div>
          </div>
        </div>
        
        <div className="filter-section">
          <div className="search-filters">
            <Input
              placeholder="搜索课程名称或任务ID"
              prefix={<SearchOutlined />}
              allowClear
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 240 }}
            />
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              value={dateRange}
              onChange={setDateRange}
              style={{ width: 280 }}
              className="date-picker"
              separator="至"
              format="YYYY-MM-DD"
              allowClear
            />
          </div>
          
          <div className="status-filters">
            <Button 
              type={activeStatus === null ? "primary" : "default"}
              onClick={() => handleStatusFilterChange(null)}
            >
              全部
            </Button>
            <Button 
              type={activeStatus === 1 ? "primary" : "default"}
              onClick={() => handleStatusFilterChange(1)}
              icon={<CheckCircleOutlined />}
            >
              成功
            </Button>
            <Button 
              type={activeStatus === 0 ? "primary" : "default"}
              onClick={() => handleStatusFilterChange(0)}
              icon={<CloseCircleOutlined />}
            >
              失败/未签到
            </Button>
            <Button onClick={resetFilters}>重置筛选</Button>
          </div>
        </div>
        
        {filteredData && filteredData.length > 0 ? (
          <Table
            columns={columns}
            dataSource={filteredData}
            rowKey={(record) => record.id || `${record.sign_in_task_id}-${record.sign_in_time || record.end_time}`}
            loading={loading && !refreshing}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
            rowClassName={(record) => {
              if (record.status === 1) return 'success-row';
              if (record.status === 0 && !record.id) return 'missed-row';
              return 'failed-row';
            }}
            onRow={(record) => ({
              onClick: () => {
                showRecordDetails(record);
              }
            })}
          />
        ) : (
          <div className="empty-container">
            <Empty 
              description={
                searchText || dateRange || activeStatus !== null ? "没有符合筛选条件的签到记录" : "暂无签到记录"
              }
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
            {(searchText || dateRange || activeStatus !== null) && (
              <Button onClick={resetFilters}>清除筛选</Button>
            )}
          </div>
        )}
      </Card>
      
      {/* 签到记录详情模态框 */}
      <Modal
        title="签到记录详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {selectedRecord && (
          <div className="record-details">
            <div className="status-header">
              {selectedRecord.status === 1 ? (
                <Badge 
                  status="success" 
                  text={<Text strong style={{ fontSize: 16 }}>签到成功</Text>} 
                />
              ) : selectedRecord.status === 0 && !selectedRecord.id ? (
                <Badge 
                  status="warning" 
                  text={<Text strong style={{ fontSize: 16 }}>未签到</Text>} 
                />
              ) : (
                <Badge 
                  status="error" 
                  text={<Text strong style={{ fontSize: 16 }}>签到失败</Text>} 
                />
              )}
            </div>
            
            <Descriptions bordered column={1} size="small">
              <Descriptions.Item label="课程名称">{selectedRecord.course_name || '未知课程'}</Descriptions.Item>
              <Descriptions.Item label="课程ID">{selectedRecord.course_id || '未知'}</Descriptions.Item>
              <Descriptions.Item label="签到任务">
                {selectedRecord.task_description || `签到任务 #${selectedRecord.sign_in_task_id}`}
              </Descriptions.Item>
              <Descriptions.Item label="任务开始时间">
                {formatTime(selectedRecord.start_time)}
              </Descriptions.Item>
              <Descriptions.Item label="任务结束时间">
                {formatTime(selectedRecord.end_time)}
              </Descriptions.Item>
              <Descriptions.Item label="签到时间">
                {selectedRecord.status === 0 && !selectedRecord.id ? 
                  '未签到' : 
                  formatTime(selectedRecord.sign_in_time)
                }
              </Descriptions.Item>
              <Descriptions.Item label="位置信息">
                {selectedRecord.location || '未记录位置信息'}
              </Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default History;